Artificial Intelligence Nanodegree

Computer Vision Capstone

Project: Facial Keypoint Detection


Welcome to the final Computer Vision project in the Artificial Intelligence Nanodegree program!

In this project, you’ll combine your knowledge of computer vision techniques and deep learning to build and end-to-end facial keypoint recognition system! Facial keypoints include points around the eyes, nose, and mouth on any face and are used in many applications, from facial tracking to emotion recognition.

There are three main parts to this project:

Part 1 : Investigating OpenCV, pre-processing, and face detection

Part 2 : Training a Convolutional Neural Network (CNN) to detect facial keypoints

Part 3 : Putting parts 1 and 2 together to identify facial keypoints on any image!


*Here's what you need to know to complete the project:

  1. In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested.

    a. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

  1. In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation.

    a. Each section where you will answer a question is preceded by a 'Question X' header.

    b. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional suggestions for enhancing the project beyond the minimum requirements. If you decide to pursue the "(Optional)" sections, you should include the code in this IPython notebook.

Your project submission will be evaluated based on your answers to each of the questions and the code implementations you provide.

Steps to Complete the Project

Each part of the notebook is further broken down into separate steps. Feel free to use the links below to navigate the notebook.

In this project you will get to explore a few of the many computer vision algorithms built into the OpenCV library. This expansive computer vision library is now almost 20 years old and still growing!

The project itself is broken down into three large parts, then even further into separate steps. Make sure to read through each step, and complete any sections that begin with '(IMPLEMENTATION)' in the header; these implementation sections may contain multiple TODOs that will be marked in code. For convenience, we provide links to each of these steps below.

Part 1 : Investigating OpenCV, pre-processing, and face detection

  • Step 0: Detect Faces Using a Haar Cascade Classifier
  • Step 1: Add Eye Detection
  • Step 2: De-noise an Image for Better Face Detection
  • Step 3: Blur an Image and Perform Edge Detection
  • Step 4: Automatically Hide the Identity of an Individual

Part 2 : Training a Convolutional Neural Network (CNN) to detect facial keypoints

  • Step 5: Create a CNN to Recognize Facial Keypoints
  • Step 6: Compile and Train the Model
  • Step 7: Visualize the Loss and Answer Questions

Part 3 : Putting parts 1 and 2 together to identify facial keypoints on any image!

  • Step 8: Build a Robust Facial Keypoints Detector (Complete the CV Pipeline)

Step 0: Detect Faces Using a Haar Cascade Classifier

Have you ever wondered how Facebook automatically tags images with your friends' faces? Or how high-end cameras automatically find and focus on a certain person's face? Applications like these depend heavily on the machine learning task known as face detection - which is the task of automatically finding faces in images containing people.

At its root face detection is a classification problem - that is a problem of distinguishing between distinct classes of things. With face detection these distinct classes are 1) images of human faces and 2) everything else.

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the detector_architectures directory.

Import Resources

In the next python cell, we load in the required libraries for this section of the project.

In [1]:
# Import required libraries for this section

%matplotlib inline

import numpy as np
import matplotlib.pyplot as plt
import math
import cv2                     # OpenCV library for computer vision
from PIL import Image
import time 

Next, we load in and display a test image for performing face detection.

Note: by default OpenCV assumes the ordering of our image's color channels are Blue, then Green, then Red. This is slightly out of order with most image types we'll use in these experiments, whose color channels are ordered Red, then Green, then Blue. In order to switch the Blue and Red channels of our test image around we will use OpenCV's cvtColor function, which you can read more about by checking out some of its documentation located here. This is a general utility function that can do other transformations too like converting a color image to grayscale, and transforming a standard color image to HSV color space.

In [2]:
# Load in color image for face detection
image = cv2.imread('images/test_image_1.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Plot our image using subplots to specify a size and title
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)
Out[2]:
<matplotlib.image.AxesImage at 0x11ac92ef0>

There are a lot of people - and faces - in this picture. 13 faces to be exact! In the next code cell, we demonstrate how to use a Haar Cascade classifier to detect all the faces in this test image.

This face detector uses information about patterns of intensity in an image to reliably detect faces under varying light conditions. So, to use this face detector, we'll first convert the image from color to grayscale.

Then, we load in the fully trained architecture of the face detector -- found in the file haarcascade_frontalface_default.xml - and use it on our image to find faces!

To learn more about the parameters of the detector see this post.

In [3]:
# Convert the RGB  image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 4, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face Detections')
ax1.imshow(image_with_detections)
Number of faces detected: 13
Out[3]:
<matplotlib.image.AxesImage at 0x11fd82588>

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.


Step 1: Add Eye Detections

There are other pre-trained detectors available that use a Haar Cascade Classifier - including full human body detectors, license plate detectors, and more. A full list of the pre-trained architectures can be found here.

To test your eye detector, we'll first read in a new test image with just a single face.

In [4]:
# Load in color image for face detection
image = cv2.imread('images/james.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Plot the RGB image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)
Out[4]:
<matplotlib.image.AxesImage at 0x11fd3d080>

Notice that even though the image is a black and white image, we have read it in as a color image and so it will still need to be converted to grayscale in order to perform the most accurate face detection.

So, the next steps will be to convert this image to grayscale, then load OpenCV's face detector and run it with parameters that detect this face accurately.

In [5]:
# Convert the RGB  image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 1.25, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face Detection')
ax1.imshow(image_with_detections)
Number of faces detected: 1
Out[5]:
<matplotlib.image.AxesImage at 0x11fdf7160>

(IMPLEMENTATION) Add an eye detector to the current face detection setup.

A Haar-cascade eye detector can be included in the same way that the face detector was and, in this first task, it will be your job to do just this.

To set up an eye detector, use the stored parameters of the eye cascade detector, called haarcascade_eye.xml, located in the detector_architectures subdirectory. In the next code cell, create your eye detector and store its detections.

A few notes before you get started:

First, make sure to give your loaded eye detector the variable name

eye_cascade

and give the list of eye regions you detect the variable name

eyes

Second, since we've already run the face detector over this image, you should only search for eyes within the rectangular face regions detected in faces. This will minimize false detections.

Lastly, once you've run your eye detector over the facial detection region, you should display the RGB image with both the face detection boxes (in red) and your eye detections (in green) to verify that everything works as expected.

In [6]:
## TODO: Add eye detection, using haarcascade_eye.xml, to the current face detector algorithm
## TODO: Loop over the eye detections and draw their corresponding boxes in green on image_with_detections

# face detection and addition to the image
def face_detection(image, verbose=False, params=(1.25, 6)):
    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

    # Detect the faces in image
    faces = face_cascade.detectMultiScale(gray, *params)

    if verbose:
        print('Number of faces detected:', len(faces))
        
    image_with_detections = np.copy(image)

    # Get the bounding box for each detected face
    for (x,y,w,h) in faces:
        cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    
    return image_with_detections


# eye detection and addition to the image
def eye_detection(image, verbose=False, params=(1.2, 6)):
    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    eye_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_eye.xml')

    # Detect the eyes in image
    eyes = eye_cascade.detectMultiScale(gray, *params)
    
    if verbose:
        print('Number of eyes detected:', len(eyes))

    image_with_detections = np.copy(image)
    
    # Loop over and add green box for each eye
    for (x,y,w,h) in eyes:
        cv2.rectangle(image_with_detections, (x,y), (x+w,y+h),(0,255,0), 3)

    return image_with_detections
In [7]:
image_with_detections = np.copy(image)

# Loop over the detections and draw their corresponding face detection boxes
for (x,y,w,h) in faces:
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h),(255,0,0), 3)  
    
# Do not change the code above this comment!

## TODO: Add eye detection, using haarcascade_eye.xml, to the current face detector algorithm
## TODO: Loop over the eye detections and draw their corresponding boxes in green on image_with_detections
image_with_detections = eye_detection(image_with_detections, True)

# Plot the image with both faces and eyes detected
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face and Eye Detection')
ax1.imshow(image_with_detections)
Number of eyes detected: 2
Out[7]:
<matplotlib.image.AxesImage at 0x11e8a33c8>

(Optional) Add face and eye detection to your laptop camera

It's time to kick it up a notch, and add face and eye detection to your laptop's camera! Afterwards, you'll be able to show off your creation like in the gif shown below - made with a completed version of the code!

Notice that not all of the detections here are perfect - and your result need not be perfect either. You should spend a small amount of time tuning the parameters of your detectors to get reasonable results, but don't hold out for perfection. If we wanted perfection we'd need to spend a ton of time tuning the parameters of each detector, cleaning up the input image frames, etc. You can think of this as more of a rapid prototype.

The next cell contains code for a wrapper function called laptop_camera_face_eye_detector that, when called, will activate your laptop's camera. You will place the relevant face and eye detection code in this wrapper function to implement face/eye detection and mark those detections on each image frame that your camera captures.

Before adding anything to the function, you can run it to get an idea of how it works - a small window should pop up showing you the live feed from your camera; you can press any key to close this window.

Note: Mac users may find that activating this function kills the kernel of their notebook every once in a while. If this happens to you, just restart your notebook's kernel, activate cell(s) containing any crucial import statements, and you'll be good to go!

In [8]:
### Add face and eye detection to this laptop camera function 
# Make sure to draw out all faces/eyes found in each frame on the shown video feed

import cv2
import time 

# wrapper function for face/eye detection with your laptop camera
def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # Try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # Keep the video stream open
    while rval:
        # operate in gray
        gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
        
        frame = face_detection(frame)
        frame = eye_detection(frame)
        
        # Plot the image from camera with all the face and eye detections marked
        cv2.imshow("face detection activated", frame)
        
        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # Exit by pressing any key
            # Destroy windows 
            cv2.destroyAllWindows()
            
            # Make sure window closes on OSx
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()    
In [9]:
# Call the laptop camera face/eye detector function above
laptop_camera_go()

Note: the function call above crashes when I use AWS GPU instance.


Step 2: De-noise an Image for Better Face Detection

Image quality is an important aspect of any computer vision task. Typically, when creating a set of images to train a deep learning network, significant care is taken to ensure that training images are free of visual noise or artifacts that hinder object detection. While computer vision algorithms - like a face detector - are typically trained on 'nice' data such as this, new test data doesn't always look so nice!

When applying a trained computer vision algorithm to a new piece of test data one often cleans it up first before feeding it in. This sort of cleaning - referred to as pre-processing - can include a number of cleaning phases like blurring, de-noising, color transformations, etc., and many of these tasks can be accomplished using OpenCV.

In this short subsection we explore OpenCV's noise-removal functionality to see how we can clean up a noisy image, which we then feed into our trained face detector.

Create a noisy image to work with

In the next cell, we create an artificial noisy version of the previous multi-face image. This is a little exaggerated - we don't typically get images that are this noisy - but image noise, or 'grainy-ness' in a digitial image - is a fairly common phenomenon.

In [16]:
# Load in the multi-face test image again
image = cv2.imread('images/test_image_1.jpg')

# Convert the image copy to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Make an array copy of this image
image_with_noise = np.asarray(image)

# Create noise - here we add noise sampled randomly from a Gaussian distribution: a common model for noise
noise_level = 40
noise = np.random.randn(image.shape[0],image.shape[1],image.shape[2])*noise_level

# Add this noise to the array image copy
image_with_noise = image_with_noise + noise

# Convert back to uint8 format
image_with_noise = np.asarray([np.uint8(np.clip(i,0,255)) for i in image_with_noise])

# Plot our noisy image!
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Noisy Image')
ax1.imshow(image_with_noise)
Out[16]:
<matplotlib.image.AxesImage at 0x1267cdf98>

In the context of face detection, the problem with an image like this is that - due to noise - we may miss some faces or get false detections.

In the next cell we apply the same trained OpenCV detector with the same settings as before, to see what sort of detections we get.

In [17]:
# Convert the RGB  image to grayscale
gray_noise = cv2.cvtColor(image_with_noise, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray_noise, 1.25, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image_with_noise)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Noisy Image with Face Detections')
ax1.imshow(image_with_detections)
Number of faces detected: 14
Out[17]:
<matplotlib.image.AxesImage at 0x1268836a0>

With this added noise we now miss one of the faces!

Note: not really, sometimes, depending on initialization, it recognizes all of them, or detects one more, or misses one :)

(IMPLEMENTATION) De-noise this image for better face detection

Time to get your hands dirty: using OpenCV's built in color image de-noising functionality called fastNlMeansDenoisingColored - de-noise this image enough so that all the faces in the image are properly detected. Once you have cleaned the image in the next cell, use the cell that follows to run our trained face detector over the cleaned image to check out its detections.

You can find its official documentation here and a useful example here.

Note: you can keep all parameters except photo_render fixed as shown in the second link above. Play around with the value of this parameter - see how it affects the resulting cleaned image.

In [18]:
## TODO: Use OpenCV's built in color image de-noising function to clean up our noisy image!
dst = cv2.fastNlMeansDenoisingColored(image_with_noise,None,16,16,7,21)

fig = plt.figure(figsize = (14,8))
plt.subplot(121),plt.imshow(image_with_noise)
plt.subplot(122),plt.imshow(dst)
plt.show()

denoised_image = dst # your final de-noised image (should be RGB)
In [20]:
## TODO: Run the face detector on the de-noised image to improve your detections and display the result
image_with_detections = face_detection(dst, True)
    
# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Noisy Image with Face Detections')
ax1.imshow(image_with_detections)
Number of faces detected: 13
Out[20]:
<matplotlib.image.AxesImage at 0x127e0b048>

Step 3: Blur an Image and Perform Edge Detection

Now that we have developed a simple pipeline for detecting faces using OpenCV - let's start playing around with a few fun things we can do with all those detected faces!

Importance of Blur in Edge Detection

Edge detection is a concept that pops up almost everywhere in computer vision applications, as edge-based features (as well as features built on top of edges) are often some of the best features for e.g., object detection and recognition problems.

Edge detection is a dimension reduction technique - by keeping only the edges of an image we get to throw away a lot of non-discriminating information. And typically the most useful kind of edge-detection is one that preserves only the important, global structures (ignoring local structures that aren't very discriminative). So removing local structures / retaining global structures is a crucial pre-processing step to performing edge detection in an image, and blurring can do just that.

Below is an animated gif showing the result of an edge-detected cat taken from Wikipedia, where the image is gradually blurred more and more prior to edge detection. When the animation begins you can't quite make out what it's a picture of, but as the animation evolves and local structures are removed via blurring the cat becomes visible in the edge-detected image.

Edge detection is a convolution performed on the image itself, and you can read about Canny edge detection on this OpenCV documentation page.

Canny edge detection

In the cell below we load in a test image, then apply Canny edge detection on it. The original image is shown on the left panel of the figure, while the edge-detected version of the image is shown on the right. Notice how the result looks very busy - there are too many little details preserved in the image before it is sent to the edge detector. When applied in computer vision applications, edge detection should preserve global structure; doing away with local structures that don't help describe what objects are in the image.

In [21]:
# Load in the image
image = cv2.imread('images/fawzia.jpg')

# Convert to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)  

# Perform Canny edge detection
edges = cv2.Canny(gray,100,200)

# Dilate the image to amplify edges
edges = cv2.dilate(edges, None)

# Plot the RGB and edge-detected image
fig = plt.figure(figsize = (15,15))
ax1 = fig.add_subplot(121)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)

ax2 = fig.add_subplot(122)
ax2.set_xticks([])
ax2.set_yticks([])

ax2.set_title('Canny Edges')
ax2.imshow(edges, cmap='gray')
Out[21]:
<matplotlib.image.AxesImage at 0x127de9ba8>

Without first blurring the image, and removing small, local structures, a lot of irrelevant edge content gets picked up and amplified by the detector (as shown in the right panel above).

(IMPLEMENTATION) Blur the image then perform edge detection

In the next cell, you will repeat this experiment - blurring the image first to remove these local structures, so that only the important boudnary details remain in the edge-detected image.

Blur the image by using OpenCV's filter2d functionality - which is discussed in this documentation page - and use an averaging kernel of width equal to 4.

In [22]:
### TODO: Blur the test imageusing OpenCV's filter2d functionality, 
# Use an averaging kernel, and a kernel width equal to 4

## TODO: Then perform Canny edge detection and display the output

# Bluring
kernel = np.ones((4,4),np.float32)/16
blur_image = cv2.filter2D(image,-1,kernel)

# Edge detection
edges = cv2.Canny(blur_image,100,200)
edges = cv2.dilate(edges, None)

# Plot the RGB and edge-detected image
fig = plt.figure(figsize = (15,15))
ax1 = fig.add_subplot(121)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Blurred Image')
ax1.imshow(blur_image)

ax2 = fig.add_subplot(122)
ax2.set_xticks([])
ax2.set_yticks([])

ax2.set_title('Blurred Image edges')
ax2.imshow(edges, cmap='gray')
Out[22]:
<matplotlib.image.AxesImage at 0x11fa31ba8>

Step 4: Automatically Hide the Identity of an Individual

If you film something like a documentary or reality TV, you must get permission from every individual shown on film before you can show their face, otherwise you need to blur it out - by blurring the face a lot (so much so that even the global structures are obscured)! This is also true for projects like Google's StreetView maps - an enormous collection of mapping images taken from a fleet of Google vehicles. Because it would be impossible for Google to get the permission of every single person accidentally captured in one of these images they blur out everyone's faces, the detected images must automatically blur the identity of detected people. Here's a few examples of folks caught in the camera of a Google street view vehicle.

Read in an image to perform identity detection

Let's try this out for ourselves. Use the face detection pipeline built above and what you know about using the filter2D to blur and image, and use these in tandem to hide the identity of the person in the following image - loaded in and printed in the next cell.

In [23]:
# Load in the image
image = cv2.imread('images/gus.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Display the image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
Out[23]:
<matplotlib.image.AxesImage at 0x11f9867f0>

(IMPLEMENTATION) Use blurring to hide the identity of an individual in an image

The idea here is to 1) automatically detect the face in this image, and then 2) blur it out! Make sure to adjust the parameters of the averaging blur filter to completely obscure this person's identity.

In [24]:
## TODO: Blur the bounding box around each detected face using an averaging filter and display the result
def blur_face(image):
    # first detect face
    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    masked_image = np.copy(image)

    # make a strong averaging kernel
    kernel = np.ones((41,41),np.float32)/1681
    blur_image = cv2.filter2D(image,-1,kernel)

    # Get the bounding box for each detected face
    for (x,y,w,h) in faces:
        # change pixel value to those of blurred image
        masked_image[y:y+h, x:x+w] = blur_image[y:y+h, x:x+w]

    return masked_image
In [25]:
## TODO: Blur the bounding box around each detected face using an averaging filter and display the result

# function is defined above
masked_face = blur_face(image)
    
# Plot the RGB and edge-detected image
fig = plt.figure(figsize = (15,15))
ax1 = fig.add_subplot(121)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original')
ax1.imshow(image)

ax2 = fig.add_subplot(122)
ax2.set_xticks([])
ax2.set_yticks([])

ax2.set_title('Blurred Face')
ax2.imshow(masked_face)
Out[25]:
<matplotlib.image.AxesImage at 0x131905b38>

(Optional) Build identity protection into your laptop camera

In this optional task you can add identity protection to your laptop camera, using the previously completed code where you added face detection to your laptop camera - and the task above. You should be able to get reasonable results with little parameter tuning - like the one shown in the gif below.

As with the previous video task, to make this perfect would require significant effort - so don't strive for perfection here, strive for reasonable quality.

The next cell contains code a wrapper function called laptop_camera_identity_hider that - when called - will activate your laptop's camera. You need to place the relevant face detection and blurring code developed above in this function in order to blur faces entering your laptop camera's field of view.

Before adding anything to the function you can call it to get a hang of how it works - a small window will pop up showing you the live feed from your camera, you can press any key to close this window.

Note: Mac users may find that activating this function kills the kernel of their notebook every once in a while. If this happens to you, just restart your notebook's kernel, activate cell(s) containing any crucial import statements, and you'll be good to go!

In [26]:
### Insert face detection and blurring code into the wrapper below to create an identity protector on your laptop!
import cv2
import time 

def laptop_camera_identity_hider():
    # Create instance of video capturer
    cv2.namedWindow("face masking activated")

    # make a strong averaging kernel
    kernel = np.ones((41,41),np.float32)/1681

    # start stream
    vc = cv2.VideoCapture(0)

    # Try to get the first frame
    if vc.isOpened():
        rval, frame = vc.read()
    else:
        rval = False
    
    # Keep the video stream open
    while rval:
        # just call the tested function
        frame = blur_face(frame)
        
        # Plot the image from camera with all the face and eye detections marked
        cv2.imshow("face detection activated", frame)
        
        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # Exit by pressing any key
            # Destroy windows 
            cv2.destroyAllWindows()
            
            # Make sure window closes on OSx
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read() 
        
In [27]:
# Run laptop identity hider
laptop_camera_identity_hider()

Note: crashed when I run it on AWS instance, works well locally on Mac.


Step 5: Create a CNN to Recognize Facial Keypoints

OpenCV is often used in practice with other machine learning and deep learning libraries to produce interesting results. In this stage of the project you will create your own end-to-end pipeline - employing convolutional networks in keras along with OpenCV - to apply a "selfie" filter to streaming video and images.

You will start by creating and then training a convolutional network that can detect facial keypoints in a small dataset of cropped images of human faces. We then guide you towards OpenCV to expanding your detection algorithm to more general images. What are facial keypoints? Let's take a look at some examples.

Facial keypoints (also called facial landmarks) are the small blue-green dots shown on each of the faces in the image above - there are 15 keypoints marked in each image. They mark important areas of the face - the eyes, corners of the mouth, the nose, etc. Facial keypoints can be used in a variety of machine learning applications from face and emotion recognition to commercial applications like the image filters popularized by Snapchat.

Below we illustrate a filter that, using the results of this section, automatically places sunglasses on people in images (using the facial keypoints to place the glasses correctly on each face). Here, the facial keypoints have been colored lime green for visualization purposes.

Make a facial keypoint detector

But first things first: how can we make a facial keypoint detector? Well, at a high level, notice that facial keypoint detection is a regression problem. A single face corresponds to a set of 15 facial keypoints (a set of 15 corresponding $(x, y)$ coordinates, i.e., an output point). Because our input data are images, we can employ a convolutional neural network to recognize patterns in our images and learn how to identify these keypoint given sets of labeled data.

In order to train a regressor, we need a training set - a set of facial image / facial keypoint pairs to train on. For this we will be using this dataset from Kaggle. We've already downloaded this data and placed it in the data directory. Make sure that you have both the training and test data files. The training dataset contains several thousand $96 \times 96$ grayscale images of cropped human faces, along with each face's 15 corresponding facial keypoints (also called landmarks) that have been placed by hand, and recorded in $(x, y)$ coordinates. This wonderful resource also has a substantial testing set, which we will use in tinkering with our convolutional network.

To load in this data, run the Python cell below - notice we will load in both the training and testing sets.

The load_data function is in the included utils.py file.

In [31]:
from utils import *

# Load training set
X_train, y_train = load_data()
print("X_train.shape == {}".format(X_train.shape))
print("y_train.shape == {}; y_train.min == {:.3f}; y_train.max == {:.3f}".format(
    y_train.shape, y_train.min(), y_train.max()))

# Load testing set
X_test, _ = load_data(test=True)
print("X_test.shape == {}".format(X_test.shape))
X_train.shape == (2140, 96, 96, 1)
y_train.shape == (2140, 30); y_train.min == -0.920; y_train.max == 0.996
X_test.shape == (1783, 96, 96, 1)

The load_data function in utils.py originates from this excellent blog post, which you are strongly encouraged to read. Please take the time now to review this function. Note how the output values - that is, the coordinates of each set of facial landmarks - have been normalized to take on values in the range $[-1, 1]$, while the pixel values of each input point (a facial image) have been normalized to the range $[0,1]$.

Note: the original Kaggle dataset contains some images with several missing keypoints. For simplicity, the load_data function removes those images with missing labels from the dataset. As an optional extension, you are welcome to amend the load_data function to include the incomplete data points.

Visualize the Training Data

Execute the code cell below to visualize a subset of the training data.

In [32]:
import matplotlib.pyplot as plt
%matplotlib inline

fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
    ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
    plot_data(X_train[i], y_train[i], ax)

For each training image, there are two landmarks per eyebrow (four total), three per eye (six total), four for the mouth, and one for the tip of the nose.

Review the plot_data function in utils.py to understand how the 30-dimensional training labels in y_train are mapped to facial locations, as this function will prove useful for your pipeline.

(IMPLEMENTATION) Specify the CNN Architecture

In this section, you will specify a neural network for predicting the locations of facial keypoints. Use the code cell below to specify the architecture of your neural network. We have imported some layers that you may find useful for this task, but if you need to use more Keras layers, feel free to import them in the cell.

Your network should accept a $96 \times 96$ grayscale image as input, and it should output a vector with 30 entries, corresponding to the predicted (horizontal and vertical) locations of 15 facial keypoints. If you are not sure where to start, you can find some useful starting architectures in this blog, but you are not permitted to copy any of the architectures that you find online.

In [33]:
# Import deep learning resources from Keras
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Dropout
from keras.layers import Flatten, Dense


## TODO: Specify a CNN architecture
# Your model should accept 96x96 pixel graysale images in
# It should have a fully-connected output layer with 30 values (2 for each facial keypoint)


# I'll package the model into a function to help with weights reset for later use
def create_model():
    model = Sequential()
    # first set of conv2D and maxpool
    model.add(Convolution2D(32, kernel_size=(5, 5), strides=(1, 1), activation='relu', input_shape=[96, 96, 1]))
    model.add(MaxPooling2D(pool_size=(2, 2)))
#     model.add(Dropout(0.2))

    # second set of conv2D and maxpool
    model.add(Convolution2D(64, (5, 5), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
#     model.add(Dropout(0.2))

    # now flatten, add one additional dense layer and output the required amount of features = 30
    model.add(Flatten())
    model.add(Dense(64, activation='relu'))
    model.add(Dense(30))
    
    return model
    
# Summarize the model
model = create_model()
model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 92, 92, 32)        832       
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 46, 46, 32)        0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 42, 42, 64)        51264     
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 21, 21, 64)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 28224)             0         
_________________________________________________________________
dense_1 (Dense)              (None, 64)                1806400   
_________________________________________________________________
dense_2 (Dense)              (None, 30)                1950      
=================================================================
Total params: 1,860,446
Trainable params: 1,860,446
Non-trainable params: 0
_________________________________________________________________

Note: we'll use fairly typical convNet architecture, with two sets of conv2D followed by maxpool. I added the dropout to avoid overfitting, although I haven't observed any even without it. At the end I added one more dense layer with relu activation, and the final dense layer with required output dimensions.


Step 6: Compile and Train the Model

After specifying your architecture, you'll need to compile and train the model to detect facial keypoints'

(IMPLEMENTATION) Compile and Train the Model

Use the compile method to configure the learning process. Experiment with your choice of optimizer; you may have some ideas about which will work best (SGD vs. RMSprop, etc), but take the time to empirically verify your theories.

Use the fit method to train the model. Break off a validation set by setting validation_split=0.2. Save the returned History object in the history variable.

Experiment with your model to minimize the validation loss (measured as mean squared error). A very good model will achieve about 0.0015 loss (though it's possible to do even better). When you have finished training, save your model as an HDF5 file with file path my_model.h5.

In [22]:
from keras.callbacks import Callback
# time callback to store execution time for comparison purposes
# inspiration: https://stackoverflow.com/questions/43178668/record-the-computation-time-for-each-epoch-in-keras-during-model-fit
class TimeHistory(Callback):
    def on_train_begin(self, logs={}):
        self.total_time = 0

    def on_epoch_begin(self, batch, logs={}):
        self.epoch_time_start = time.time()

    def on_epoch_end(self, batch, logs={}):
        self.total_time += time.time() - self.epoch_time_start
In [41]:
from keras.optimizers import SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax, Nadam
from keras.callbacks import ModelCheckpoint
from keras.initializers import glorot_uniform


## TODO: Compile the model
# we'll use MSE as loss as this is the regression problem
# we'll also do several optimizers
opts = ['rmsprop', 'sgd', 'adagrad', 'adadelta', 'adam', 'adamax', 'nadam']

# init result dicts
times = {}
train_losses = {}
val_losses = {}

for _o in opts:
    print("Training using {}".format(_o))

    # reset weights
    model = create_model()
    
    # compile and go
    model.compile(loss='mean_squared_error', optimizer=_o)

    ## TODO: Train the model
    checkpointer = ModelCheckpoint(filepath='{}_best_weights.h5'.format(_o), verbose=1, save_best_only=True)
    timer = TimeHistory()
    hist = model.fit(X_train, y_train, batch_size=128, epochs=40, verbose=0,
                 validation_split=0.2, callbacks=[checkpointer, timer])

    # store results
    times[_o] = timer.total_time
    train_losses[_o] = hist.history['loss']
    val_losses[_o] = hist.history['val_loss']
    print("=============\n")

    ## TODO: Save the model as model.h5
    model.save('{}_my_model.h5'.format(_o))
    

# save results to avoid re-fitting everytime after jupyter restart
import pickle

with open('train_losses.pickle', 'wb') as _f:
    pickle.dump(train_losses, _f)
with open('val_losses.pickle', 'wb') as _f:
    pickle.dump(val_losses, _f)
with open('times.pickle', 'wb') as _f:
    pickle.dump(times, _f)
Training using rmsprop
Epoch 00000: val_loss improved from inf to 0.07964, saving model to rmsprop_best_weights.h5
Epoch 00001: val_loss improved from 0.07964 to 0.07614, saving model to rmsprop_best_weights.h5
Epoch 00002: val_loss improved from 0.07614 to 0.05009, saving model to rmsprop_best_weights.h5
Epoch 00003: val_loss improved from 0.05009 to 0.03398, saving model to rmsprop_best_weights.h5
Epoch 00004: val_loss improved from 0.03398 to 0.01674, saving model to rmsprop_best_weights.h5
Epoch 00005: val_loss improved from 0.01674 to 0.00973, saving model to rmsprop_best_weights.h5
Epoch 00006: val_loss improved from 0.00973 to 0.00794, saving model to rmsprop_best_weights.h5
Epoch 00007: val_loss improved from 0.00794 to 0.00736, saving model to rmsprop_best_weights.h5
Epoch 00008: val_loss did not improve
Epoch 00009: val_loss improved from 0.00736 to 0.00720, saving model to rmsprop_best_weights.h5
Epoch 00010: val_loss improved from 0.00720 to 0.00667, saving model to rmsprop_best_weights.h5
Epoch 00011: val_loss improved from 0.00667 to 0.00647, saving model to rmsprop_best_weights.h5
Epoch 00012: val_loss improved from 0.00647 to 0.00508, saving model to rmsprop_best_weights.h5
Epoch 00013: val_loss did not improve
Epoch 00014: val_loss improved from 0.00508 to 0.00424, saving model to rmsprop_best_weights.h5
Epoch 00015: val_loss did not improve
Epoch 00016: val_loss did not improve
Epoch 00017: val_loss did not improve
Epoch 00018: val_loss did not improve
Epoch 00019: val_loss did not improve
Epoch 00020: val_loss improved from 0.00424 to 0.00365, saving model to rmsprop_best_weights.h5
Epoch 00021: val_loss did not improve
Epoch 00022: val_loss did not improve
Epoch 00023: val_loss improved from 0.00365 to 0.00363, saving model to rmsprop_best_weights.h5
Epoch 00024: val_loss did not improve
Epoch 00025: val_loss improved from 0.00363 to 0.00353, saving model to rmsprop_best_weights.h5
Epoch 00026: val_loss improved from 0.00353 to 0.00339, saving model to rmsprop_best_weights.h5
Epoch 00027: val_loss did not improve
Epoch 00028: val_loss did not improve
Epoch 00029: val_loss did not improve
Epoch 00030: val_loss improved from 0.00339 to 0.00300, saving model to rmsprop_best_weights.h5
Epoch 00031: val_loss improved from 0.00300 to 0.00290, saving model to rmsprop_best_weights.h5
Epoch 00032: val_loss did not improve
Epoch 00033: val_loss did not improve
Epoch 00034: val_loss did not improve
Epoch 00035: val_loss improved from 0.00290 to 0.00259, saving model to rmsprop_best_weights.h5
Epoch 00036: val_loss did not improve
Epoch 00037: val_loss did not improve
Epoch 00038: val_loss did not improve
Epoch 00039: val_loss improved from 0.00259 to 0.00217, saving model to rmsprop_best_weights.h5
=============

Training using sgd
Epoch 00000: val_loss improved from inf to 0.06966, saving model to sgd_best_weights.h5
Epoch 00001: val_loss improved from 0.06966 to 0.05290, saving model to sgd_best_weights.h5
Epoch 00002: val_loss improved from 0.05290 to 0.04194, saving model to sgd_best_weights.h5
Epoch 00003: val_loss improved from 0.04194 to 0.03505, saving model to sgd_best_weights.h5
Epoch 00004: val_loss improved from 0.03505 to 0.03031, saving model to sgd_best_weights.h5
Epoch 00005: val_loss improved from 0.03031 to 0.02660, saving model to sgd_best_weights.h5
Epoch 00006: val_loss improved from 0.02660 to 0.02331, saving model to sgd_best_weights.h5
Epoch 00007: val_loss improved from 0.02331 to 0.02061, saving model to sgd_best_weights.h5
Epoch 00008: val_loss improved from 0.02061 to 0.01835, saving model to sgd_best_weights.h5
Epoch 00009: val_loss improved from 0.01835 to 0.01651, saving model to sgd_best_weights.h5
Epoch 00010: val_loss improved from 0.01651 to 0.01503, saving model to sgd_best_weights.h5
Epoch 00011: val_loss improved from 0.01503 to 0.01387, saving model to sgd_best_weights.h5
Epoch 00012: val_loss improved from 0.01387 to 0.01296, saving model to sgd_best_weights.h5
Epoch 00013: val_loss improved from 0.01296 to 0.01225, saving model to sgd_best_weights.h5
Epoch 00014: val_loss improved from 0.01225 to 0.01165, saving model to sgd_best_weights.h5
Epoch 00015: val_loss improved from 0.01165 to 0.01118, saving model to sgd_best_weights.h5
Epoch 00016: val_loss improved from 0.01118 to 0.01084, saving model to sgd_best_weights.h5
Epoch 00017: val_loss improved from 0.01084 to 0.01051, saving model to sgd_best_weights.h5
Epoch 00018: val_loss improved from 0.01051 to 0.01025, saving model to sgd_best_weights.h5
Epoch 00019: val_loss improved from 0.01025 to 0.01009, saving model to sgd_best_weights.h5
Epoch 00020: val_loss improved from 0.01009 to 0.00989, saving model to sgd_best_weights.h5
Epoch 00021: val_loss improved from 0.00989 to 0.00971, saving model to sgd_best_weights.h5
Epoch 00022: val_loss improved from 0.00971 to 0.00962, saving model to sgd_best_weights.h5
Epoch 00023: val_loss improved from 0.00962 to 0.00947, saving model to sgd_best_weights.h5
Epoch 00024: val_loss improved from 0.00947 to 0.00935, saving model to sgd_best_weights.h5
Epoch 00025: val_loss improved from 0.00935 to 0.00926, saving model to sgd_best_weights.h5
Epoch 00026: val_loss improved from 0.00926 to 0.00916, saving model to sgd_best_weights.h5
Epoch 00027: val_loss improved from 0.00916 to 0.00908, saving model to sgd_best_weights.h5
Epoch 00028: val_loss improved from 0.00908 to 0.00900, saving model to sgd_best_weights.h5
Epoch 00029: val_loss improved from 0.00900 to 0.00894, saving model to sgd_best_weights.h5
Epoch 00030: val_loss improved from 0.00894 to 0.00885, saving model to sgd_best_weights.h5
Epoch 00031: val_loss improved from 0.00885 to 0.00878, saving model to sgd_best_weights.h5
Epoch 00032: val_loss improved from 0.00878 to 0.00872, saving model to sgd_best_weights.h5
Epoch 00033: val_loss improved from 0.00872 to 0.00865, saving model to sgd_best_weights.h5
Epoch 00034: val_loss improved from 0.00865 to 0.00859, saving model to sgd_best_weights.h5
Epoch 00035: val_loss improved from 0.00859 to 0.00852, saving model to sgd_best_weights.h5
Epoch 00036: val_loss improved from 0.00852 to 0.00848, saving model to sgd_best_weights.h5
Epoch 00037: val_loss improved from 0.00848 to 0.00841, saving model to sgd_best_weights.h5
Epoch 00038: val_loss improved from 0.00841 to 0.00835, saving model to sgd_best_weights.h5
Epoch 00039: val_loss improved from 0.00835 to 0.00831, saving model to sgd_best_weights.h5
=============

Training using adagrad
Epoch 00000: val_loss improved from inf to 0.05565, saving model to adagrad_best_weights.h5
Epoch 00001: val_loss improved from 0.05565 to 0.04595, saving model to adagrad_best_weights.h5
Epoch 00002: val_loss did not improve
Epoch 00003: val_loss did not improve
Epoch 00004: val_loss did not improve
Epoch 00005: val_loss improved from 0.04595 to 0.04455, saving model to adagrad_best_weights.h5
Epoch 00006: val_loss improved from 0.04455 to 0.04346, saving model to adagrad_best_weights.h5
Epoch 00007: val_loss improved from 0.04346 to 0.04245, saving model to adagrad_best_weights.h5
Epoch 00008: val_loss improved from 0.04245 to 0.04155, saving model to adagrad_best_weights.h5
Epoch 00009: val_loss improved from 0.04155 to 0.04087, saving model to adagrad_best_weights.h5
Epoch 00010: val_loss improved from 0.04087 to 0.04023, saving model to adagrad_best_weights.h5
Epoch 00011: val_loss improved from 0.04023 to 0.03959, saving model to adagrad_best_weights.h5
Epoch 00012: val_loss improved from 0.03959 to 0.03352, saving model to adagrad_best_weights.h5
Epoch 00013: val_loss improved from 0.03352 to 0.03254, saving model to adagrad_best_weights.h5
Epoch 00014: val_loss improved from 0.03254 to 0.03173, saving model to adagrad_best_weights.h5
Epoch 00015: val_loss improved from 0.03173 to 0.03090, saving model to adagrad_best_weights.h5
Epoch 00016: val_loss improved from 0.03090 to 0.03000, saving model to adagrad_best_weights.h5
Epoch 00017: val_loss did not improve
Epoch 00018: val_loss improved from 0.03000 to 0.02946, saving model to adagrad_best_weights.h5
Epoch 00019: val_loss improved from 0.02946 to 0.02840, saving model to adagrad_best_weights.h5
Epoch 00020: val_loss did not improve
Epoch 00021: val_loss improved from 0.02840 to 0.02668, saving model to adagrad_best_weights.h5
Epoch 00022: val_loss did not improve
Epoch 00023: val_loss improved from 0.02668 to 0.02525, saving model to adagrad_best_weights.h5
Epoch 00024: val_loss did not improve
Epoch 00025: val_loss improved from 0.02525 to 0.02419, saving model to adagrad_best_weights.h5
Epoch 00026: val_loss improved from 0.02419 to 0.02234, saving model to adagrad_best_weights.h5
Epoch 00027: val_loss improved from 0.02234 to 0.02200, saving model to adagrad_best_weights.h5
Epoch 00028: val_loss improved from 0.02200 to 0.02089, saving model to adagrad_best_weights.h5
Epoch 00029: val_loss did not improve
Epoch 00030: val_loss did not improve
Epoch 00031: val_loss improved from 0.02089 to 0.02036, saving model to adagrad_best_weights.h5
Epoch 00032: val_loss improved from 0.02036 to 0.02031, saving model to adagrad_best_weights.h5
Epoch 00033: val_loss did not improve
Epoch 00034: val_loss improved from 0.02031 to 0.01851, saving model to adagrad_best_weights.h5
Epoch 00035: val_loss improved from 0.01851 to 0.01788, saving model to adagrad_best_weights.h5
Epoch 00036: val_loss improved from 0.01788 to 0.01690, saving model to adagrad_best_weights.h5
Epoch 00037: val_loss improved from 0.01690 to 0.01530, saving model to adagrad_best_weights.h5
Epoch 00038: val_loss improved from 0.01530 to 0.01459, saving model to adagrad_best_weights.h5
Epoch 00039: val_loss did not improve
=============

Training using adadelta
Epoch 00000: val_loss improved from inf to 0.03768, saving model to adadelta_best_weights.h5
Epoch 00001: val_loss improved from 0.03768 to 0.01714, saving model to adadelta_best_weights.h5
Epoch 00002: val_loss improved from 0.01714 to 0.01414, saving model to adadelta_best_weights.h5
Epoch 00003: val_loss improved from 0.01414 to 0.01228, saving model to adadelta_best_weights.h5
Epoch 00004: val_loss improved from 0.01228 to 0.01063, saving model to adadelta_best_weights.h5
Epoch 00005: val_loss improved from 0.01063 to 0.01007, saving model to adadelta_best_weights.h5
Epoch 00006: val_loss did not improve
Epoch 00007: val_loss improved from 0.01007 to 0.00748, saving model to adadelta_best_weights.h5
Epoch 00008: val_loss did not improve
Epoch 00009: val_loss improved from 0.00748 to 0.00728, saving model to adadelta_best_weights.h5
Epoch 00010: val_loss improved from 0.00728 to 0.00649, saving model to adadelta_best_weights.h5
Epoch 00011: val_loss improved from 0.00649 to 0.00556, saving model to adadelta_best_weights.h5
Epoch 00012: val_loss did not improve
Epoch 00013: val_loss did not improve
Epoch 00014: val_loss did not improve
Epoch 00015: val_loss improved from 0.00556 to 0.00518, saving model to adadelta_best_weights.h5
Epoch 00016: val_loss did not improve
Epoch 00017: val_loss improved from 0.00518 to 0.00404, saving model to adadelta_best_weights.h5
Epoch 00018: val_loss did not improve
Epoch 00019: val_loss did not improve
Epoch 00020: val_loss did not improve
Epoch 00021: val_loss did not improve
Epoch 00022: val_loss did not improve
Epoch 00023: val_loss did not improve
Epoch 00024: val_loss did not improve
Epoch 00025: val_loss did not improve
Epoch 00026: val_loss improved from 0.00404 to 0.00391, saving model to adadelta_best_weights.h5
Epoch 00027: val_loss did not improve
Epoch 00028: val_loss did not improve
Epoch 00029: val_loss improved from 0.00391 to 0.00349, saving model to adadelta_best_weights.h5
Epoch 00030: val_loss did not improve
Epoch 00031: val_loss did not improve
Epoch 00032: val_loss did not improve
Epoch 00033: val_loss did not improve
Epoch 00034: val_loss did not improve
Epoch 00035: val_loss did not improve
Epoch 00036: val_loss did not improve
Epoch 00037: val_loss did not improve
Epoch 00038: val_loss improved from 0.00349 to 0.00321, saving model to adadelta_best_weights.h5
Epoch 00039: val_loss did not improve
=============

Training using adam
Epoch 00000: val_loss improved from inf to 0.06431, saving model to adam_best_weights.h5
Epoch 00001: val_loss improved from 0.06431 to 0.03240, saving model to adam_best_weights.h5
Epoch 00002: val_loss improved from 0.03240 to 0.01349, saving model to adam_best_weights.h5
Epoch 00003: val_loss improved from 0.01349 to 0.00621, saving model to adam_best_weights.h5
Epoch 00004: val_loss improved from 0.00621 to 0.00462, saving model to adam_best_weights.h5
Epoch 00005: val_loss improved from 0.00462 to 0.00403, saving model to adam_best_weights.h5
Epoch 00006: val_loss improved from 0.00403 to 0.00377, saving model to adam_best_weights.h5
Epoch 00007: val_loss did not improve
Epoch 00008: val_loss improved from 0.00377 to 0.00352, saving model to adam_best_weights.h5
Epoch 00009: val_loss improved from 0.00352 to 0.00343, saving model to adam_best_weights.h5
Epoch 00010: val_loss did not improve
Epoch 00011: val_loss improved from 0.00343 to 0.00336, saving model to adam_best_weights.h5
Epoch 00012: val_loss improved from 0.00336 to 0.00326, saving model to adam_best_weights.h5
Epoch 00013: val_loss did not improve
Epoch 00014: val_loss improved from 0.00326 to 0.00323, saving model to adam_best_weights.h5
Epoch 00015: val_loss improved from 0.00323 to 0.00319, saving model to adam_best_weights.h5
Epoch 00016: val_loss improved from 0.00319 to 0.00316, saving model to adam_best_weights.h5
Epoch 00017: val_loss improved from 0.00316 to 0.00309, saving model to adam_best_weights.h5
Epoch 00018: val_loss did not improve
Epoch 00019: val_loss improved from 0.00309 to 0.00306, saving model to adam_best_weights.h5
Epoch 00020: val_loss improved from 0.00306 to 0.00305, saving model to adam_best_weights.h5
Epoch 00021: val_loss improved from 0.00305 to 0.00297, saving model to adam_best_weights.h5
Epoch 00022: val_loss improved from 0.00297 to 0.00296, saving model to adam_best_weights.h5
Epoch 00023: val_loss improved from 0.00296 to 0.00293, saving model to adam_best_weights.h5
Epoch 00024: val_loss improved from 0.00293 to 0.00290, saving model to adam_best_weights.h5
Epoch 00025: val_loss improved from 0.00290 to 0.00289, saving model to adam_best_weights.h5
Epoch 00026: val_loss improved from 0.00289 to 0.00286, saving model to adam_best_weights.h5
Epoch 00027: val_loss improved from 0.00286 to 0.00284, saving model to adam_best_weights.h5
Epoch 00028: val_loss did not improve
Epoch 00029: val_loss improved from 0.00284 to 0.00278, saving model to adam_best_weights.h5
Epoch 00030: val_loss improved from 0.00278 to 0.00278, saving model to adam_best_weights.h5
Epoch 00031: val_loss improved from 0.00278 to 0.00278, saving model to adam_best_weights.h5
Epoch 00032: val_loss did not improve
Epoch 00033: val_loss did not improve
Epoch 00034: val_loss improved from 0.00278 to 0.00268, saving model to adam_best_weights.h5
Epoch 00035: val_loss improved from 0.00268 to 0.00267, saving model to adam_best_weights.h5
Epoch 00036: val_loss improved from 0.00267 to 0.00264, saving model to adam_best_weights.h5
Epoch 00037: val_loss improved from 0.00264 to 0.00262, saving model to adam_best_weights.h5
Epoch 00038: val_loss improved from 0.00262 to 0.00258, saving model to adam_best_weights.h5
Epoch 00039: val_loss improved from 0.00258 to 0.00256, saving model to adam_best_weights.h5
=============

Training using adamax
Epoch 00000: val_loss improved from inf to 0.07311, saving model to adamax_best_weights.h5
Epoch 00001: val_loss improved from 0.07311 to 0.03718, saving model to adamax_best_weights.h5
Epoch 00002: val_loss improved from 0.03718 to 0.01753, saving model to adamax_best_weights.h5
Epoch 00003: val_loss improved from 0.01753 to 0.00923, saving model to adamax_best_weights.h5
Epoch 00004: val_loss improved from 0.00923 to 0.00633, saving model to adamax_best_weights.h5
Epoch 00005: val_loss improved from 0.00633 to 0.00514, saving model to adamax_best_weights.h5
Epoch 00006: val_loss improved from 0.00514 to 0.00441, saving model to adamax_best_weights.h5
Epoch 00007: val_loss improved from 0.00441 to 0.00433, saving model to adamax_best_weights.h5
Epoch 00008: val_loss improved from 0.00433 to 0.00414, saving model to adamax_best_weights.h5
Epoch 00009: val_loss improved from 0.00414 to 0.00402, saving model to adamax_best_weights.h5
Epoch 00010: val_loss improved from 0.00402 to 0.00392, saving model to adamax_best_weights.h5
Epoch 00011: val_loss improved from 0.00392 to 0.00388, saving model to adamax_best_weights.h5
Epoch 00012: val_loss improved from 0.00388 to 0.00377, saving model to adamax_best_weights.h5
Epoch 00013: val_loss improved from 0.00377 to 0.00349, saving model to adamax_best_weights.h5
Epoch 00014: val_loss improved from 0.00349 to 0.00343, saving model to adamax_best_weights.h5
Epoch 00015: val_loss improved from 0.00343 to 0.00319, saving model to adamax_best_weights.h5
Epoch 00016: val_loss did not improve
Epoch 00017: val_loss improved from 0.00319 to 0.00304, saving model to adamax_best_weights.h5
Epoch 00018: val_loss did not improve
Epoch 00019: val_loss improved from 0.00304 to 0.00294, saving model to adamax_best_weights.h5
Epoch 00020: val_loss improved from 0.00294 to 0.00289, saving model to adamax_best_weights.h5
Epoch 00021: val_loss did not improve
Epoch 00022: val_loss improved from 0.00289 to 0.00278, saving model to adamax_best_weights.h5
Epoch 00023: val_loss improved from 0.00278 to 0.00274, saving model to adamax_best_weights.h5
Epoch 00024: val_loss improved from 0.00274 to 0.00271, saving model to adamax_best_weights.h5
Epoch 00025: val_loss did not improve
Epoch 00026: val_loss did not improve
Epoch 00027: val_loss improved from 0.00271 to 0.00269, saving model to adamax_best_weights.h5
Epoch 00028: val_loss improved from 0.00269 to 0.00249, saving model to adamax_best_weights.h5
Epoch 00029: val_loss improved from 0.00249 to 0.00249, saving model to adamax_best_weights.h5
Epoch 00030: val_loss improved from 0.00249 to 0.00235, saving model to adamax_best_weights.h5
Epoch 00031: val_loss improved from 0.00235 to 0.00230, saving model to adamax_best_weights.h5
Epoch 00032: val_loss did not improve
Epoch 00033: val_loss improved from 0.00230 to 0.00221, saving model to adamax_best_weights.h5
Epoch 00034: val_loss did not improve
Epoch 00035: val_loss did not improve
Epoch 00036: val_loss improved from 0.00221 to 0.00211, saving model to adamax_best_weights.h5
Epoch 00037: val_loss did not improve
Epoch 00038: val_loss improved from 0.00211 to 0.00208, saving model to adamax_best_weights.h5
Epoch 00039: val_loss did not improve
=============

Training using nadam
Epoch 00000: val_loss improved from inf to 0.11854, saving model to nadam_best_weights.h5
Epoch 00001: val_loss improved from 0.11854 to 0.09228, saving model to nadam_best_weights.h5
Epoch 00002: val_loss improved from 0.09228 to 0.06165, saving model to nadam_best_weights.h5
Epoch 00003: val_loss improved from 0.06165 to 0.04405, saving model to nadam_best_weights.h5
Epoch 00004: val_loss improved from 0.04405 to 0.03342, saving model to nadam_best_weights.h5
Epoch 00005: val_loss improved from 0.03342 to 0.02341, saving model to nadam_best_weights.h5
Epoch 00006: val_loss improved from 0.02341 to 0.01586, saving model to nadam_best_weights.h5
Epoch 00007: val_loss improved from 0.01586 to 0.01247, saving model to nadam_best_weights.h5
Epoch 00008: val_loss improved from 0.01247 to 0.00977, saving model to nadam_best_weights.h5
Epoch 00009: val_loss improved from 0.00977 to 0.00851, saving model to nadam_best_weights.h5
Epoch 00010: val_loss improved from 0.00851 to 0.00773, saving model to nadam_best_weights.h5
Epoch 00011: val_loss improved from 0.00773 to 0.00696, saving model to nadam_best_weights.h5
Epoch 00012: val_loss did not improve
Epoch 00013: val_loss did not improve
Epoch 00014: val_loss improved from 0.00696 to 0.00663, saving model to nadam_best_weights.h5
Epoch 00015: val_loss improved from 0.00663 to 0.00632, saving model to nadam_best_weights.h5
Epoch 00016: val_loss improved from 0.00632 to 0.00599, saving model to nadam_best_weights.h5
Epoch 00017: val_loss improved from 0.00599 to 0.00560, saving model to nadam_best_weights.h5
Epoch 00018: val_loss improved from 0.00560 to 0.00517, saving model to nadam_best_weights.h5
Epoch 00019: val_loss did not improve
Epoch 00020: val_loss improved from 0.00517 to 0.00485, saving model to nadam_best_weights.h5
Epoch 00021: val_loss did not improve
Epoch 00022: val_loss did not improve
Epoch 00023: val_loss did not improve
Epoch 00024: val_loss improved from 0.00485 to 0.00453, saving model to nadam_best_weights.h5
Epoch 00025: val_loss did not improve
Epoch 00026: val_loss did not improve
Epoch 00027: val_loss improved from 0.00453 to 0.00440, saving model to nadam_best_weights.h5
Epoch 00028: val_loss improved from 0.00440 to 0.00438, saving model to nadam_best_weights.h5
Epoch 00029: val_loss did not improve
Epoch 00030: val_loss did not improve
Epoch 00031: val_loss improved from 0.00438 to 0.00426, saving model to nadam_best_weights.h5
Epoch 00032: val_loss improved from 0.00426 to 0.00406, saving model to nadam_best_weights.h5
Epoch 00033: val_loss did not improve
Epoch 00034: val_loss did not improve
Epoch 00035: val_loss did not improve
Epoch 00036: val_loss did not improve
Epoch 00037: val_loss did not improve
Epoch 00038: val_loss did not improve
Epoch 00039: val_loss did not improve
=============


Step 7: Visualize the Loss and Test Predictions

(IMPLEMENTATION) Answer a few questions and visualize the loss

Question 1: Outline the steps you took to get to your final neural network architecture and your reasoning at each step.

Answer: I used the standard convolutional network architecture with conv2D layers followed by maxpooling layers, which was shown to be a good combination. I started with 32 kernels layer, followed by 64 layer. Overall this combination provided a 4 times reduction in spatial dimensions and 64 depth features at the end of convolutional part of the network. It was followed by flattening layer prior to passing it through densely connected layers. I then added a fully connected layer with relu activation to help finding connections between flattened convolutional features and final targets. I've chosen it to be relatively small, just of size of 64 nodes, which is roughly 2 times larger than the size of the target vector. Such last dense layers have a very large impact on the total number of parameters in a network, so I didn't want it to have too many nodes. The final layer is just a linear dense layer to convert the 64 features to required 30 targets.

Question 2: Defend your choice of optimizer. Which optimizers did you test, and how did you determine which worked best?

Answer: I tested all listed optimizers (see the graph below). Among all of them adam and rmsprop achieve the best validation loss (MSE), although the difference is not dramatic after 40 epochs. RMSprop, however, manages to do it in the least amount of time, so my conclusion is that it is the most suited for this particular regression task.

Use the code cell below to plot the training and validation loss of your neural network. You may find this resource useful.

In [38]:
## TODO: Visualize the training and validation loss of your neural network

opts = ['rmsprop', 'sgd', 'adagrad', 'adadelta', 'adam', 'adamax', 'nadam']

# load results to avoid re-fitting everytime after jupyter restart
import pickle
train_losses = pickle.load(open('train_losses.pickle', 'rb'))
val_losses = pickle.load(open('val_losses.pickle', 'rb'))
times = pickle.load(open('times.pickle', 'rb'))


fig = plt.figure(figsize = (20,5))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.2, wspace=0.2)

for i in range(len(opts)):
    # this is for axis sharing
    if i > 0:
        ax = fig.add_subplot(1, len(opts), i+1, sharey=ax)
    else:
        ax = fig.add_subplot(1, len(opts), i+1)
    ax.semilogy(train_losses[opts[i]], label='train loss')
    ax.semilogy(val_losses[opts[i]], label='valid loss')
    ax.set_title("{}, time {:5.3f}".format(opts[i], times[opts[i]]))
    ax.legend(loc='upper right')
    plt.ylim([1e-3, 1])

Question 3: Do you notice any evidence of overfitting or underfitting in the above plot? If so, what steps have you taken to improve your model? Note that slight overfitting or underfitting will not hurt your chances of a successful submission, as long as you have attempted some solutions towards improving your model (such as regularization, dropout, increased/decreased number of layers, etc).

Answer: I don't see evidence of major over or underfitting in any these plots. There is no significant difference between train and validation loss. Both curves decrease fairly monotonically and equidistantly in most of the cases. The Adam optimizer shows some separation between train and validation losses after 30 epochs, but at that time the validation loss is already at the lowest value among all optimizers, so it is likely that 30-35 epochs is the right number for this particular architecture and dataset. I have also verified the architecture with Dropout after every MaxPool layer and it resulted in a larger gap between train and validation losses after ~30 epochs. In addition to this the validation loss with Dropout(0.2) layers was higher at 30 epochs than without them.

Visualize a Subset of the Test Predictions

Execute the code cell below to visualize your model's predicted keypoints on a subset of the testing images.

In [39]:
model.load_weights("rmsprop_my_model.h5")

y_test = model.predict(X_test)

fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)

for i in range(9):
    ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
    plot_data(X_test[i], y_test[i], ax)

Step 8: Complete the pipeline

With the work you did in Sections 1 and 2 of this notebook, along with your freshly trained facial keypoint detector, you can now complete the full pipeline. That is given a color image containing a person or persons you can now

  • Detect the faces in this image automatically using OpenCV
  • Predict the facial keypoints in each face detected in the image
  • Paint predicted keypoints on each face detected

In this Subsection you will do just this!

(IMPLEMENTATION) Facial Keypoints Detector

Use the OpenCV face detection functionality you built in previous Sections to expand the functionality of your keypoints detector to color images with arbitrary size. Your function should perform the following steps

  1. Accept a color image.
  2. Convert the image to grayscale.
  3. Detect and crop the face contained in the image.
  4. Locate the facial keypoints in the cropped image.
  5. Overlay the facial keypoints in the original (color, uncropped) image.

Note: step 4 can be the trickiest because remember your convolutional network is only trained to detect facial keypoints in $96 \times 96$ grayscale images where each pixel was normalized to lie in the interval $[0,1]$, and remember that each facial keypoint was normalized during training to the interval $[-1,1]$. This means - practically speaking - to paint detected keypoints onto a test face you need to perform this same pre-processing to your candidate face - that is after detecting it you should resize it to $96 \times 96$ and normalize its values before feeding it into your facial keypoint detector. To be shown correctly on the original image the output keypoints from your detector then need to be shifted and re-normalized from the interval $[-1,1]$ to the width and height of your detected face.

When complete you should be able to produce example images like the one below

In [57]:
# function to detect and draw faces and facepoints
def facepoints_detection(image, verbose=False):
    
    # load model and face_cascade
    model.load_weights("rmsprop_my_model.h5")
    face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

    # Face detection - Haar on gray image
    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    
    # get the cropped faces
    cropped_faces = []
    for (x,y,w,h) in faces:
        cropped_faces.append(gray[y:y+h, x:x+w])

    # resize cropped faces and normalize pixels
    resized_cropped_faces = [cv2.resize(_f, (96, 96))/255 for _f in cropped_faces]

    # reshape to right format and prepare to feed to the model
    X_faces = np.array([_f.reshape(96, 96, 1) for _f in resized_cropped_faces])
    if verbose:
        print("Shape of X_faces {}".format(X_faces.shape))

    # run through the facepoints model
    # do only if faces have been detected - to work with streaming version
    if len(faces) > 0:
        y_faces = model.predict(X_faces)
        if verbose:
            print("Shape of y_faces {}".format(y_faces.shape))

    # # plot the intermediate result to verify
    # fig = plt.figure(figsize=(10,5))
    # for i in range(len(faces)):
    #     ax = fig.add_subplot(1, len(faces), i + 1, xticks=[], yticks=[])
    #     ax.set_title('intermediate 96x96')
    #     plot_data(X_cropped_faces[i], y_faces[i], ax)

        # reconstruct y_faces to 96x96 size and upscale to original image
        real_faces = (y_faces*48+48)
        for _f in range(len(faces)):
            real_faces[_f][0::2] = real_faces[_f][0::2]*cropped_faces[_f].shape[0]/96
            real_faces[_f][1::2] = real_faces[_f][1::2]*cropped_faces[_f].shape[1]/96

    # # plot the intermediate result to verify
    # fig = plt.figure(figsize=(10,5))
    # for i in range(len(faces)):
    #     ax = fig.add_subplot(1, len(faces), i + 1, xticks=[], yticks=[])
    #     ax.set_title('intermediate original')
    #     ax.imshow(cropped_faces[i], cmap='gray')
    #     ax.scatter(real_faces[i][0::2], 
    #         real_faces[i][1::2], 
    #         marker='o', 
    #         c='c', 
    #         s=40)

    # Make a copy of the orginal image to draw face detections on
    image_copy = np.copy(image)

    # Get the bounding box for each detected face
    for (x,y,w,h) in faces:
        # Add a red bounding box to the detections image
        cv2.rectangle(image_copy, (x,y), (x+w,y+h), (255,0,0), 3)

    # now draw circles where features are with offset by face coordinate
    if len(faces) > 0:
        for _i, coords in enumerate(faces):
            for _idx in range(0, real_faces.shape[1], 2):
                cv2.circle(img=image_copy,
                           center=(int(real_faces[_i][_idx]+coords[0]), int(real_faces[_i][_idx+1]+coords[1])),
                           radius=3,color=(0,255,0),thickness=-1)
    
    return image_copy
In [58]:
# Load in color image for face detection
image = cv2.imread('images/obamas4.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

### TODO: Use the face detection code we saw in Section 1 with your trained conv-net 
## TODO : Paint the predicted keypoints on the test image

facepoints_image = facepoints_detection(image, True)
    
# Display the image with the face boxes and facepoints
fig = plt.figure(figsize = (15,15))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Image with Detections')
ax1.imshow(facepoints_image)
Shape of X_faces (2, 96, 96, 1)
Shape of y_faces (2, 30)
Out[58]:
<matplotlib.image.AxesImage at 0x11d9d3978>

(Optional) Further Directions - add a filter using facial keypoints to your laptop camera

Now you can add facial keypoint detection to your laptop camera - as illustrated in the gif below.

The next Python cell contains the basic laptop video camera function used in the previous optional video exercises. Combine it with the functionality you developed for keypoint detection and marking in the previous exercise and you should be good to go!

In [62]:
import cv2
import time 
from keras.models import load_model

def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("facepoints detection activated")
    vc = cv2.VideoCapture(0)

    # Try to get the first frame
    if vc.isOpened():
        rval, frame = vc.read()
    else:
        rval = False
    
    # Keep the video stream open
    while rval:
        # just run the tested model on every frame
        frame = facepoints_detection(frame)
        
        # Plot the image from camera with all the face and eye detections marked
        cv2.imshow("facepoints", frame)
        
        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # Exit by pressing any key
            # Destroy windows 
            cv2.destroyAllWindows()
            
            # Make sure window closes on OSx
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read() 
In [63]:
# Run your keypoint face painter
laptop_camera_go()

Note: developed and tested locally. Running on AWS GPU instance crashes in my case. The only issue I've observed is that the facepoint for bottom lip is not perfect and does not always detect open mouth well enough.

(Optional) Further Directions - add a filter using facial keypoints

Using your freshly minted facial keypoint detector pipeline you can now do things like add fun filters to a person's face automatically. In this optional exercise you can play around with adding sunglasses automatically to each individual's face in an image as shown in a demonstration image below.

To produce this effect an image of a pair of sunglasses shown in the Python cell below.

In [64]:
# Load in sunglasses image - note the usage of the special option
# cv2.IMREAD_UNCHANGED, this option is used because the sunglasses 
# image has a 4th channel that allows us to control how transparent each pixel in the image is
sunglasses = cv2.imread("images/sunglasses_4.png", cv2.IMREAD_UNCHANGED)

# Plot the image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.imshow(sunglasses)
ax1.axis('off');

This image is placed over each individual's face using the detected eye points to determine the location of the sunglasses, and eyebrow points to determine the size that the sunglasses should be for each person (one could also use the nose point to determine this).

Notice that this image actually has 4 channels, not just 3.

In [65]:
# Print out the shape of the sunglasses image
print ('The sunglasses image has shape: ' + str(np.shape(sunglasses)))
The sunglasses image has shape: (1123, 3064, 4)

It has the usual red, blue, and green channels any color image has, with the 4th channel representing the transparency level of each pixel in the image. Here's how the transparency channel works: the lower the value, the more transparent the pixel will become. The lower bound (completely transparent) is zero here, so any pixels set to 0 will not be seen.

This is how we can place this image of sunglasses on someone's face and still see the area around of their face where the sunglasses lie - because these pixels in the sunglasses image have been made completely transparent.

Lets check out the alpha channel of our sunglasses image in the next Python cell. Note because many of the pixels near the boundary are transparent we'll need to explicitly print out non-zero values if we want to see them.

In [66]:
# Print out the sunglasses transparency (alpha) channel
alpha_channel = sunglasses[:,:,3]
print ('the alpha channel here looks like')
print (alpha_channel)

# Just to double check that there are indeed non-zero values
# Let's find and print out every value greater than zero
values = np.where(alpha_channel != 0)
print ('\n the non-zero values of the alpha channel look like')
print (values)
the alpha channel here looks like
[[0 0 0 ... 0 0 0]
 [0 0 0 ... 0 0 0]
 [0 0 0 ... 0 0 0]
 ...
 [0 0 0 ... 0 0 0]
 [0 0 0 ... 0 0 0]
 [0 0 0 ... 0 0 0]]

 the non-zero values of the alpha channel look like
(array([  17,   17,   17, ..., 1109, 1109, 1109]), array([ 687,  688,  689, ..., 2376, 2377, 2378]))

This means that when we place this sunglasses image on top of another image, we can use the transparency channel as a filter to tell us which pixels to overlay on a new image (only the non-transparent ones with values greater than zero).

One last thing: it's helpful to understand which keypoint belongs to the eyes, mouth, etc. So, in the image below, we also display the index of each facial keypoint directly on the image so that you can tell which keypoints are for the eyes, eyebrows, etc.

With this information, you're well on your way to completing this filtering task! See if you can place the sunglasses automatically on the individuals in the image loaded in / shown in the next Python cell.

In [67]:
# Load in color image for face detection
image = cv2.imread('images/obamas4.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Plot the image
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
Out[67]:
<matplotlib.image.AxesImage at 0x1291b1dd8>
In [75]:
## (Optional) TODO: Use the face detection code we saw in Section 1 with your trained conv-net to put
## sunglasses on the individuals in our test image

def draw_sunglasses(image):
    model = load_model('rmsprop_my_model.h5')
    face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

    # Face detection - Haar on gray image
    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    # Make a copy of the orginal image to draw face detections on
    image_copy = np.copy(image)

    # get the cropped faces
    cropped_faces = []
    for (x,y,w,h) in faces:
        cropped_faces.append(gray[y:y+h, x:x+w])
    
    # resize cropped faces and normalize pixels
    resized_cropped_faces = [cv2.resize(_f, (96, 96))/255 for _f in cropped_faces]

    # reshape to right format and feed to model
    X_faces = np.array([_f.reshape(96, 96, 1) for _f in resized_cropped_faces])
    
    # once again wrap the model part in conditional statement to work with streaming version
    if len(faces) > 0:
        y_faces = model.predict(X_faces)

        # reconstruct y_faces to 96x96 size and upscale to original image
        real_faces = (y_faces*48+48)
        for _f in range(len(faces)):
            real_faces[_f][0::2] = real_faces[_f][0::2]*cropped_faces[_f].shape[0]/96
            real_faces[_f][1::2] = real_faces[_f][1::2]*cropped_faces[_f].shape[1]/96
    
    '''
    Sunglass fitting section
    will be called only if len(faces) > 0
    '''
    
    # fit sunglasses
    for _f, coords in enumerate(faces):
        # auxiliary vars
        xs = int(np.min([real_faces[_f][18], real_faces[_f][10]]))+coords[0]
        ys = int(np.min([real_faces[_f][19], real_faces[_f][17], real_faces[_f][15]]))+coords[1]

        xe = int(np.max([real_faces[_f][14], real_faces[_f][6]]))+coords[0]
        ye = int(np.max([real_faces[_f][9], real_faces[_f][3], real_faces[_f][1]]))+coords[1]

        # some aesthetical adjustments
        height = int((ye - ys)*1.8)
        width = int((xe - xs)*1.14)
        xs = int(xs - width * 0.07)
        ys = int(ys - height * 0.07)

        # resize sunglasses
        resized = cv2.resize(sunglasses, (width, height))

        # take alpha as a mask and inverse mask
        alpha = resized[:, :, 3]
        alpha_inv = cv2.bitwise_not(alpha)

        # remove alpha from sunglasses
        resized = resized[:, :, :3]

        # create a ROI
        roi = image_copy[ys:ys+height, xs:xs+width]

        # Now black-out the area of glasses in ROI
        img1_bg = cv2.bitwise_and(roi,roi,mask = alpha_inv)

        # Take only positive alpha from sunglass image
        img2_fg = cv2.bitwise_and(resized,resized,mask = alpha)

        # Put it in ROI and modify the main image
        dst = cv2.add(img1_bg,img2_fg)
        image_copy[ys:ys+height, xs:xs+width] = dst
    
    return image_copy

# for _i, coords in enumerate(faces):
#     ax1.scatter(real_faces[_i][0::2]+coords[0],
#                 real_faces[_i][1::2]+coords[1],
#                 marker='o', c='c', s=40)
#     for _idx in range(0, real_faces.shape[1], 2):
#         ax1.annotate((_idx, _idx+1), (real_faces[_i][_idx]+coords[0], real_faces[_i][_idx+1]+coords[1]))
In [76]:
image_with_sunglasses = draw_sunglasses(image)

# Display the image with the face boxes and facepoints
fig = plt.figure(figsize = (15,15))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Image with Sunglasses')
ax1.imshow(image_with_sunglasses)
Out[76]:
<matplotlib.image.AxesImage at 0x15e832828>

(Optional) Further Directions - add a filter using facial keypoints to your laptop camera

Now you can add the sunglasses filter to your laptop camera - as illustrated in the gif below.

The next Python cell contains the basic laptop video camera function used in the previous optional video exercises. Combine it with the functionality you developed for adding sunglasses to someone's face in the previous optional exercise and you should be good to go!

In [77]:
import cv2
import time
import numpy as np

def laptop_camera_go():
   # Create instance of video capturer
    cv2.namedWindow("Sunglass filter is activated")
    vc = cv2.VideoCapture(0)

    # Try to get the first frame
    if vc.isOpened():
        rval, frame = vc.read()
    else:
        rval = False
    
    # Keep the video stream open
    while rval:

        # just call a tested function
        frame = draw_sunglasses(frame)
        cv2.imshow("Like a boss", frame)

        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # Exit by pressing any key
            # Destroy windows 
            cv2.destroyAllWindows()
            
            # Make sure window closes on OSx
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read() 
In [78]:
# Run sunglasses painter
laptop_camera_go()

Note: tested locally.